'''
Created on Nov 7, 2009

@author: mkiyer
'''

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import math
    
def plot_histogram(data, xlabel='x', ylabel='y', outfile=None):
    data = np.array(data)
    print 'average', np.average(data)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    nbins=100
    # the histogram of the data
    n, bins, patches = ax.hist(data, bins=nbins, facecolor='green', alpha=0.5, log=False, normed=0)
    plt.axvline(x=np.average(data), linewidth=4, color='r')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    #n, bins, patches = ax.hist(x2, bins=bins, facecolor='red', alpha=0.25)
    #l, = plt.plot(bins, mlab.normpdf(bins, 0.0, 1.0), 'r--', label='fit', linewidth=3)
    #legend([l, patches[0]], ['fit', 'hist'])
    ax.grid(True)
    if outfile is None:
        plt.show()
    else:
        plt.savefig(outfile)
    plt.close()
    return

def plot_scatter(data, 
                 outfile=None,
                 xlabel='Control Group',
                 ylabel='Experimental Group',
                 title='Coverage scatter plot'):  
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.title(title)

    #sorted_data = sorted(data, operator.itemgetter(0))
    
    xdata = [d[0] for d in data]
    ydata = [d[1] for d in data]
    # size?
    # s = 20*np.log(np.array([x.ratio for x in intervals]))        
    # color?
    # c = [x.category * cm.jet.N / len(category_names)] * len(intervals)
    # c = x.category * cm.jet.N / len(category_names)
    plt.scatter(xdata, ydata, 
                s=30, c='b', marker='o', cmap=None, norm=None,
                vmin=None, vmax=None, alpha=1.0, linewidths=None,
                verts=None)

    if outfile is None:
        plt.show()
    else:
        plt.savefig(outfile)
    plt.close()
    
    return    
    #ax.set_xscale('log')
    #ax.set_yscale('log')

    plt.axvline(x=np.average(xdata), linewidth=4, color='r')
    plt.axhline(y=np.average(ydata), linewidth=4, color='g')
    
    print 'x', np.average(xdata)
    print 'y', 'avg', np.average(ydata), 'min', np.min(ydata), 'max', np.max(ydata)
    
    # label=category_names[category])
    #plt.legend()
    # best fit line
    sorted_data = sorted(data, key=operator.itemgetter(0))
    x, y = [d[0] for d in sorted_data], [d[1] for d in sorted_data]    
    m = np.polyfit(x, y, 1)
    yfit = np.polyval(m, x)
    plt.plot(x, yfit, 'g')
    # correlation coefficient
    c = np.corrcoef(xdata, ydata)[0,1]
    r2 = c**2
    plt.figtext(0.815, 0.013, ' r^2=%.3f' % r2, color='black', weight='roman',
               size='small')    
    plt.grid()
    themax = max(x[-1], y[-1])
    plt.axis([-10, themax, -10, themax])
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)